<?php

//session_start();

require_once LIBRARIES_ENTITIES_DATABASE;
require_once LIBRARIES_ENTITIES_ITEMS;
require_once LIBRARIES_TOOLS_UTILITY;
require_once LIBRARIES_TOOLS_XTEMPLATE;
require_once LIBRARIES_TOOLS_PAGERFRONTEND;
require_once LIBRARIES_ENTITIES_ITEMPROPERTIES;

class Controller {

    public function invoke() {

        $view = '';
        if (isset($_GET['view'])) {
            $view = $_GET['view'];
        }

        $item = '';
        if (isset($_GET['item'])) {
            $item = $_GET['item'];
        }

        $action = '';
        if (isset($_POST['action'])) {
            $action = $_POST['action'];
        }

        // kiểm tra có chức năng đặt hàng không, nếu có thì hiển thị nút đặt hàng và các thông tin liên qua
        $configuration = new Configuration();
        $xmlFile = ROOT . DS . 'configuration.xml';
        $configuration->getConfiguration($xmlFile);
        $isSalse = false;
        if ($configuration->getSales() == 1) {
            $isSalse = true;
        }





        if ($view == 'categories') {
            $derectory = dirname(__FILE__);
            $xtemplate = new XTemplate($derectory . DS . 'views' . DS . 'item_list.html');

            // category alias
            $categoryAlias = $_GET['alias'];
            $items = $this->getItemsByCategoryAlias($categoryAlias);


            if ($items != null) {
                // current page
                $currentPage = 1;
                if (isset($_GET["page"])) {
                    $currentPage = $_GET["page"];
                }

                $pager = PagerFrontEnd::getPagerData(count($items), LINE_PER_PAGE, $currentPage);

                $index = 1;

                // loop each item
                foreach ($items as $item) {



                    if ($index == 1) {
                        // get category name at the first item
                        $xtemplate->assign('CATEGORY_TITLE', $item->getCategory()->getTitle());
                    }

                    if ($index > $pager->offset && $index <= $pager->limit) {

                        // get days between createdDate and current date
                        $daysBetweenDate = Utility::daysBetweenDate($item->getCreatedDate(), Utility::getCurrentDate());

                        // if days <= 3 then show new icon
                        if ($daysBetweenDate <= 3) {
                            $xtemplate->parse('main.item_list.new_icon');
                        }



                        if($index % 3 ==0){
                             $xtemplate->assign('clearfix', '<div class="clearfix"></div>');
                        }else{
                            $xtemplate->assign('clearfix', '');
                        }

                        $xtemplate->assign('ITEM_ID', $item->getID());
                        $xtemplate->assign('ITEM_IMAGE', $item->getImage());
                        $xtemplate->assign('ITEM_ALIAS', $item->getAlias());
                         $xtemplate->assign('ITEM_NAME',  mb_strtoupper($item->getName(), 'UTF-8'));
                       
                         $xtemplate->assign('ITEM_PRICE', Utility::formatToCurrencyString($item->getPrice()));

                        $xtemplate->assign('ITEM_CODE', $item->getCode());
                        $xtemplate->assign('ITEM_DATE', $item->getModifiedDate());
                        $xtemplate->assign('ITEM_DESCRIPTION', $item->getDescription());
                        
                        
                        // nếu có chức năng đặt hàng thì hiển thị giá và nút thêm vào giỏ hàng
                        if ($isSalse) {
                            $xtemplate->parse('main.item_list.price');
                            $xtemplate->parse('main.item_list.add_to_cart_button');
                        }
                        $xtemplate->parse('main.item_list');
                        
                    }
                    $index++;
                }
                $xtemplate->assign('PAGING', $pager->paging);
                $xtemplate->assign('CURRENT_PAGE', $currentPage);
                $xtemplate->assign('AMOUNT_OF_PAGE', $pager->numPages);

                $xtemplate->parse('main');
                $xtemplate->out('main');
            } else {
                echo 'không tồn tại dữ liệu';
            }
        } else if ($view == 'item') {

            $itemAlias = $_GET['alias'];
            $item = $this->getItemByAlias($itemAlias);

            if ($item != null) {
                $derectory = dirname(__FILE__);
                $xtemplate = new XTemplate($derectory . DS . 'views' . DS . 'item_detail.html');

                // category detail
                $xtemplate->assign('CATEGORY_ALIAS', $item->getCategory()->getAlias());
                $xtemplate->assign('CATEGORY_ID', $item->getCategory()->getID());
                $xtemplate->assign('CATEGORY_TITLE', $item->getCategory()->getTitle());



                // article detail
                $xtemplate->assign('ITEM_ID', $item->getID());
                $xtemplate->assign('ITEM_NAME', $item->getName());
                $xtemplate->assign('ITEM_PRICE', Utility::formatToCurrencyString($item->getPrice()));
                $xtemplate->assign('ITEM_TITLE', $item->getName());
                $xtemplate->assign('ITEM_CODE', $item->getCode());
                $xtemplate->assign('ITEM_IMAGE', $item->getImage());
                $xtemplate->assign('ITEM_DESCRIPTION', $item->getDescription());
                $xtemplate->assign('ITEM_DETAIL', $item->getDetail());
                $xtemplate->assign('ITEM_DETAIL', $item->getDetail());


                if ($isSalse) {
                    $xtemplate->parse('main.price');
                    $xtemplate->parse('main.code');
                    $xtemplate->parse('main.quantity');
                    $xtemplate->parse('main.add_to_cart_button');
                }

                // get property list of an item
                $itemProperties = $this->getItemPropertiesByItemID($item->getID());


                if ($itemProperties != null && $configuration->getSales() == 1) {

                    // propertyname list of item
                    $propertyNameListOfItem = array();

                    for ($i = 0; $i < count($itemProperties); $i++) {
                        if ($i == 0) {
                            $propertyNameListOfItem[] = $itemProperties[$i]->getProperty()->getName();
                        } else if ($itemProperties[$i]->getPropertyID() != $itemProperties[$i - 1]->getPropertyID()) {
                            $propertyNameListOfItem[] = $itemProperties[$i]->getProperty()->getName();
                        }
                    }

                    // print property value list of each property
                    for ($i = 0; $i < count($propertyNameListOfItem); $i++) {
                        $xtemplate->assign('ITEM_PROPERTY_NAME', $propertyNameListOfItem[$i]);

                        for ($y = 0; $y < count($itemProperties); $y++) {
                            if ($itemProperties[$y]->getProperty()->getName() == $propertyNameListOfItem[$i]) {
                                $xtemplate->assign('ITEM_PROPERTY_VALUE', $itemProperties[$y]->getValue());
                                $xtemplate->assign('PROPERTY_ID', $itemProperties[$y]->getPropertyID());
                                $xtemplate->assign('ITEM_PROPERTY_ID', $itemProperties[$y]->getID());
                                $xtemplate->parse('main.property_list.property_value_list');
                            }
                        }
                        $xtemplate->parse('main.property_list');
                    }
                }





                // article list of the same category
                $itemsOfTheSameCategory = $this->getItemsOfTheSameCategory($item->getCategoryID(), $item->getOrder());

                // if not null
                // show article list of the same category
                if ($itemsOfTheSameCategory != null) {
                    $index=1;
                    foreach ($itemsOfTheSameCategory as $value) {
                        $xtemplate->assign('ITEM_ALIAS_OF_THE_SAME_CATEGORY', $value->getAlias());
                        $xtemplate->assign('ITEM_ID_OF_THE_SAME_CATEGORY', $value->getID());
                        $xtemplate->assign('ITEM_NAME_OF_THE_SAME_CATEGORY',  mb_strtoupper($value->getName(), 'UTF-8'));
                        $xtemplate->assign('ITEM_IMAGE_OF_THE_SAME_CATEGORY', $value->getImage());
                        $xtemplate->assign('ITEM_DESCRIPTION_OF_THE_SAME_CATEGORY', $value->getDescription());
                        $xtemplate->assign('ITEM_PRICE_OF_THE_SAME_CATEGORY', Utility::formatToCurrencyString($value->getPrice()));
                        if ($isSalse) {
                            $xtemplate->parse('main.item_list_of_the_same_category.item_of_the_same_category.price');
                        }
                         if($index % 3 ==0){
                             $xtemplate->assign('clearfix', '<div class="clearfix"></div>');
                        }else{
                            $xtemplate->assign('clearfix', '');
                        }

                        $xtemplate->parse('main.item_list_of_the_same_category.item_of_the_same_category');
                        $index++;
                    }
                    $xtemplate->parse('main.item_list_of_the_same_category');
                }
                $xtemplate->parse('main');
                $xtemplate->out('main');
            } else {
                echo 'không tồn tại dữ liệu';
            }
        } else {
            // neu khong co vie thi tro ve trang chu
            Utility::redirect('.');
        }
    }

    // get article list by category alias
    private function getItemsByCategoryAlias($categoryAlias) {
        $db = new Database();
        try {

            // get a category by alias
            $category = new Categories();
            $category->setAlias($categoryAlias);
            $category = $category->getByAlias($db);

            if ($category != null) {
                // get article list by category id
                $item = new Items();
                $item->setCategoryID($category->getID());
                $result = $item->getListByCategoryID($db);
                $db->submitChanges();
                return $result;
            } else {
                return null;
            }
        } catch (PDOException $exc) {
            echo $exc->getMessage();
            $db->rollback();
        }
    }

    // tai chi tiet 1 bai viet boi alias
//    private function getItemByID($itemID) {
//        $db = new Database();
//        try {
//            $item = new Items();
//            $item->setID($itemID);
//            $result = $item->getByAlias($db);
//            $db->submitChanges();
//            return $result;
//        }
//        catch (PDOException $exc) {
//            echo $exc->getMessage();
//            $db->rollback();
//        }
//    }
    // get item properties of an item
    private function getItemPropertiesByItemID($itemID) {
        $db = new Database();
        try {
            $itemProperty = new ItemProperties();
            $itemProperty->setItemID($itemID);
            $result = $itemProperty->getItemPropertiesByItemID($db);
            $db->submitChanges();
            return $result;
        } catch (PDOException $exc) {
            echo $exc->getMessage();
            $db->rollback();
        }
    }

    // tai chi tiet 1 bai viet boi alias
    private function getItemByAlias($articleAlias) {
        $db = new Database();
        try {
            $item = new Items();
            $item->setAlias($articleAlias);
            $result = $item->getByAlias($db);
            $db->submitChanges();
            return $result;
        } catch (PDOException $exc) {
            echo $exc->getMessage();
            $db->rollback();
        }
    }

    /**
     * get article list of the same category but have smaller order
     * @param type $categoryID
     * @param type $order
     * @return type: article list     
     */
    private function getItemsOfTheSameCategory($categoryID, $order) {
        $db = new Database();
        try {
            $item = new Items();
            $item->setOrder($order);
            $item->setCategoryID($categoryID);
            $result = $item->getListOfTheSameCategory($db);
            $db->submitChanges();
            return $result;
        } catch (PDOException $exc) {
            echo $exc->getMessage();
            $db->rollback();
        }
    }

}

?>
